<template>
  <div style="height: 100%">
    <a-spin :spinning="isTableLoading" wrapperClassName="spinning-container">
      <div class="header-container" ref="headerContainer">
        <page-header class="header" :title="l('LoginLogs')"></page-header>
        <a-card :bordered="false">
          <a-form a-form :layout="'vertical'" @submit.prevent="getSearchData()">
            <a-row :gutter="8">
              <!-- 日期选择框 -->
              <a-col :sm="4">
                <a-form-item :label="l('DateRange')">
                  <a-range-picker
                    :placeholder="[l('StartDateTime'), l('EndDateTime')]"
                    v-model:value="startToEnd"
                  />
                </a-form-item>
              </a-col>
              <!-- 用户名搜索框 -->
              <a-col :sm="8">
                <a-form-item
                  :label="l('UserName')"
                  v-if="isGranted('Pages.Administration.LoginLogs.Query')"
                >
                  <a-input-search
                    name="username"
                    :placeholder="l('UserName')"
                    enterButton
                    v-model:value="username"
                    @search="getSearchData()"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <a-row :gutter="8">
            <a-col :md="20" :sm="12">
              <!-- 登录日志统计按钮 -->
              <a-button
                :type="'primary'"
                @click="logsDetails()"
                v-if="isGranted('Pages.Administration.LoginLogs.LoginStatistics')"
              >
                <span>{{ l('LoginStatistics') }}</span>
              </a-button>
            </a-col>
          </a-row>
        </a-card>
      </div>
      <div class="table-container">
        <!-- 表格 -->
        <a-table
          size="middle"
          :scroll="{ x: tableWidthScroll, y: tableHeightScroll }"
          :rowKey="(dataIndex) => dataIndex"
          :columns="columns"
          :data-source="dataList"
          :pagination="{
            total: totalItems,
            current: pageNumber,
            pageSize: pageSize,
            showTotal: showTotalInfo,
            showQuickJumper: true,
            showSizeChanger: true,
            change: pageNumberChange,
            showSizeChange: pageNumberChange,
            pageSizeOptions: pageSizeOptions,
            size: 'middle',
          }"
          @change="tableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'result'">
              <p>{{ l(record.result) }}</p>
            </template>
            <template v-if="column.key === 'creationTime'">
              <p>{{ _moment(record.creationTime) }}</p>
            </template>
            <template v-if="column.key === 'actions'">
              <div>
                <a
                  class="table-edit"
                  @click="logsDetails(record)"
                  v-if="isGranted('Pages.Administration.LoginLogs.LogingLogs')"
                >
                  <edit-outlined />
                  {{ l('LoginLogs') }}
                </a>
              </div>
            </template>
          </template>
        </a-table>
      </div>
    </a-spin>
  </div>
</template>

<script lang="ts">
  import { ColumnType } from 'ant-design-vue/lib/table';
  import dayjs, { Dayjs } from 'dayjs';
  import { defineComponent } from 'vue';
  import { PagedListingComponentBase } from '/@/shared/component-base';
  import { IPagedRequestDto } from '/@/shared/component-base/interfaces';
  import { LoginLogsServiceProxy } from '/@/shared/service-proxies';
  import { LoginLogsDto } from '/@/shared/service-proxies/service-proxies';
  import LogDetailsCompent from './log-details/log-details.vue';
  import { Moment } from 'moment';
  dayjs.locale('zh-cn');

  type RangeValue = [Dayjs, Dayjs];
  export default defineComponent({
    name: 'user-logs',
    mixins: [PagedListingComponentBase],
    data() {
      return {
        username: '',
        startToEnd: new Array<Moment>(),
        selectedCount: 0,
        userLogsService: new LoginLogsServiceProxy(),
        dataList: new Array<LoginLogsDto>(),
        ranges: {} as any,
      };
    },
    mounted() {
      //日期范围
      this.ranges[this.l('Today')] = [
        dayjs().add(0 - (dayjs().hour() as number), 'hour'),
        dayjs(),
      ] as RangeValue;
      this.ranges[this.l('InTheLastThreeDays')] = [dayjs().add(-3, 'day'), dayjs()] as RangeValue;
    },
    methods: {
      //数据加载
      fetchDataList(request: IPagedRequestDto, finishedCallback?: () => void) {
        console.info(this.startToEnd);
        this.userLogsService
          .getPageUserLog(
            this.username,
            this.startToEnd == null ? undefined : this.startToEnd[0],
            this.startToEnd == null ? undefined : this.startToEnd[1],
            request.maxResultCount,
            request.skipCount,
          )
          .finally(() => {
            finishedCallback!();
          })
          .then((res) => {
            this.showPaging(res);
          });
      },
      //表格列初始化
      getColumns(): ColumnType<LoginLogsDto>[] {
        return [
          {
            title: 'No',
            customRender: ({ index }) => {
              const a = (this.pageNumber - 1) * this.pageSize + (index + 1);
              return a;
            },
            width: 60,
            fixed: 'left',
          },
          {
            title: this.l('UserName'),
            dataIndex: 'userName',
            key: 'userName',
            width: 200,
            ellipsis: true,
          },
          {
            title: this.l('TeanancyName'),
            dataIndex: 'teanancyName',
            key: 'teanancyName',
            width: 200,
            ellipsis: true,
          },
          // {
          //   title: this.l('UserNameOrEmailAddress'),
          //   dataIndex: 'userNameOrEmailAddress',
          //   key: 'userNameOrEmailAddress',
          //   width: 200,
          //   ellipsis: true,
          // },
          {
            title: this.l('IpAddress'),
            dataIndex: 'clientIpAddress',
            key: 'clientIpAddress',
            width: 200,
            ellipsis: true,
          },
          {
            title: this.l('Client'),
            dataIndex: 'clientName',
            key: 'clientName',
            width: 200,
            ellipsis: true,
          },
          {
            title: this.l('LoginState'),
            dataIndex: 'result',
            key: 'result',
            width: 200,
            ellipsis: true,
          },
          {
            title: this.l('Time'),
            dataIndex: 'creationTime',
            key: 'creationTime',
            width: 200,
            ellipsis: true,
            sorter: {
              multiple: 0,
            },
          },
          {
            title: this.l('Actions'),
            dataIndex: 'actions',
            key: 'actions',
            width: 250,
            fixed: 'right',
          },
        ];
      },
      //模态框弹出
      logsDetails(item?: LoginLogsDto): void {
        this.modalHelper
          .create(
            LogDetailsCompent,
            { id: item?.userId, userName: item?.userName },
            {
              width: '800px',
            },
          )
          .subscribe(() => {});
      },
    },
  });
</script>
